<?php
	//***************************【模板调用函数】***********************************
	//为了模板方便调用，函数命名尽量简洁，容易记
	
	// print_r 调试输出格式
	function pp($data,$die=true){
		echo '<pre>';
		print_r($data);
		echo '</pre>';
		if($die) die;
	}
	
	//获取当前网址头
	function get_host($s=false){
		$host=$_SERVER['HTTP_HOST'];
		if(strstr($host,'127.0.0.')){
			return 'http://'.$host;
		}else{
			if($s){
				return 'https://'.$host;
			}else{
				return 'http://'.$host;
			}
		}
	}

	//读取字段状态对应的中文
	function status_str($field,$val){
		$conf=require(C('STATUS_CONF_PATH'));
		return $conf[$field][$val];
	}
	
	//获取当前URLGET的传值数据 返回数组
	function get_url_data(){
		$get_data=$_GET;
		unset($get_data['_URL_']);
		return $get_data;
	}
	
	//追加当前URL的GET传值函数
	function set_url_get($action='',$data=[]){
		$get_data=$_GET;
		unset($get_data['_URL_']);
		$new_data=array_merge($get_data,$data);
		$req=request();
		$action=$req->controller().'/'.$req->action();
		return U($action,$new_data);
	}
	
	//删除当前URL的GET的某个传值函数	支持数组和字符串
	function del_url_get($data){
		$get_data=$_GET;
		unset($get_data['_URL_']);
		if(in_array($data)){
			foreach($data as $d){
				unset($get_data[$d]);
			}
		}else{
			unset($get_data[$data]);
		}
		return U('',$get_data);
	}
	
	//价格显示的格式
	function price($val){
		return number_format($val,2);
	}

	//价格显示的格式保留一位小数
	function price_one($val){
		return number_format($val,1);
	}
	
	//价格小数点后面的格式
	function price_dot($val,$type=1){
		$price=format_number($val,'float');
		$price=explode('.',$price);
		return $price[$type];
	}
	
	//商品折扣格式
	function rebate($number){
		return format_number($number*10,'floats',1);
	}
	
	//数字的换算
	function format_number($num,$type,$length=2){
		switch($type){
			case 'float':								//四舍五入保留小数
				$num=sprintf('%.'.$length.'f', $num);
				break;
			case 'floats':								//不四舍五入保修小数
				$num=sprintf('%.'.$length.'f',substr(sprintf('%.'.($length+1).'f', $num), 0, -$length));
				break;	
			case 'int':									//四舍五入整数
				$num=ceil($num);
				break;
			case 'ints':								//不四舍五入整数
				$num=floor($num);
				break;
			default:
				break;
		}
		return $num;
	}
	
	//格式化时间展示
	function uc_time_ago($ptime) {
		date_default_timezone_set('PRC');
		//$ptime = strtotime($ptime);
		$etime = time() - $ptime;
		switch ($etime){
			case $etime <= 60:
				$msg = '刚刚';
				break;
			case $etime > 60 && $etime <= 60 * 60:
				$msg = floor($etime / 60) . ' 分钟前';
				break;
			case $etime > 60 * 60 && $etime <= 24 * 60 * 60:
				$msg = date('Ymd',$ptime)==date('Ymd',time()) ? '今天 '.date('H:i',$ptime) : '昨天 '.date('H:i',$ptime);
				break;
			case $etime > 24 * 60 * 60 && $etime <= 2 * 24 * 60 * 60:
				$msg = date('Ymd',$ptime)+1==date('Ymd',time()) ? '昨天 '.date('H:i',$ptime) : '前天 '.date('H:i',$ptime);
				break;
			// case $etime > 2 * 24 * 60 * 60 && $etime <= 12 * 30 * 24 * 60 * 60:
			// 	$msg = date('Y',$ptime)==date('Y',time()) ? date('m-d H:i',$ptime) : date('Y-m-d H:i',$ptime);
			// 	break;
			default: $msg = date('Y-m-d',$ptime);
		}
		return $msg;
	}

	//数字转金额大写
	function cny($ns) {
		if($ns==0) return "零元"; 
    	static $cnums=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"), 
        $cnyunits=array("元","角","分"), 
        $grees=array("拾","佰","仟","万","拾","佰","仟","亿");
	    @list($ns1,$ns2)=explode(".",$ns,2); 
	    @$ns2=array_filter(array($ns2[1],$ns2[0])); 
	    $ret=array_merge($ns2,array(implode("",_cny_map_unit(str_split($ns1),$grees)),"")); 
	    $ret=implode("",array_reverse(_cny_map_unit($ret,$cnyunits)));
	    $str=str_replace(array_keys($cnums),$cnums,$ret);
	    if(!strpos($str,'角') && !strpos($str,'分')){
	    	$str.='整';
	    }
	    return $str;
	}

	//数字转金额大写 子函数
	function _cny_map_unit($list,$units) { 
	    $ul=count($units); 
	    $xs=array(); 
	    foreach (array_reverse($list) as $x) { 
	        $l=count($xs); 
	        if ($x!="0" || !($l%4)) @$n=($x=='0'?'':$x).($units[($l-1)%$ul]); 
	        else @$n=is_numeric($xs[0][0])?$x:''; 
	        array_unshift($xs,$n); 
	    } 
	    return $xs; 
	}
	
	//跨控制器调用生成URL路径
	function span_url($url,$array=array(),$type=1){
		switch($type){
			case 1:									//确保传送 token sid wecha did
				$new_arr=array();
				if(I('get.token')!='') $new_arr['token']=I('get.token');
				if(I('get.sid')!='') $new_arr['sid']=I('get.sid');
				if(I('get.wechat')!='') $new_arr['wechat']=I('get.wechat');
				if(I('get.did')!='') $new_arr['did']=I('get.did');
				$array=array_merge($array,$new_arr);
				break;
		}
		return U($url,$array);
	}
	
	//生成加载JS文件语句 可批量
	function include_js($array,$diy=false){
		//开启$diy 则不读取系统模板路径替换参数
		$str='';
		$tmpl_path=config('view.tpl_replace_string');
		foreach($array as $path=>$data){
			foreach($data as $val){
				if($diy){
					$js_path=$path.$val;
				}else{
					$tmpl_str=$tmpl_path[$path];
					if($tmpl_str!='') $tmpl_str.='/';
					$js_path=$tmpl_str.$val;
				}
				$str.='<script type="text/javascript" src="'.$js_path.'"></script>';
			}
		}
		return $str;
	}
	
	//Ueditor编辑器后台初始化函数
	function ueditor_init($type=1){
		$tool_path=env('path.tool_path');
		$str="<script>window.UEDITOR_HOME_URL='".$tool_path."/ueditor/';</script>";		//路径必须在导入JS之前设置					
		$data=[																	//调入Ueditor 的JS文件
			$tool_path=>[
				'/ueditor/ueditor.config.js',
				'/ueditor/ueditor.all.min.js'
			],
		];
		$str.=include_js($data,true);
		$str.="<script>";	
		switch($type){
			case 1:																		//后台调用编辑器初始化
				$img_path=env('upload.up_img_path').'editor/';										//管理员图片上传地址			
				$str.='window.UEDITOR_CONFIG.elementPathEnabled=false;';
				$str.="UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
						UE.Editor.prototype.getActionUrl = function(action) {
							if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
								return '".U('Ueditor/imageUp')."';
							} else if (action == 'listimage') {
								return '".U('Ueditor/imageManager')."';
							} else if (action == 'uploadvideo') {
								return 'http://a.b.com/video.php';
							} else {
								return this._bkGetActionUrl.call(this, action);
							}
						}";
				break;
			case 2:
				break;
		}
		$str.='</script>';
		echo $str;
	}
	
	
	//Ueditor编辑器配置函数
	function ueditor($name,$width,$height,$type='common',$source=true,$autoHeight=0){
		// source 为 true 时则为后台调用编辑器， 为 false 时则为前台调用编辑器，读取不同配置
		$conf=[
			'fullscreen',
			'bold','italic','underline','fontborder','strikethrough','superscript','subscript','removeformat','formatmatch','autotypeset','blockquote','pasteplain','|',
			'forecolor','backcolor','insertorderedlist','insertunorderedlist','selectall','cleardoc','|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft','justifycenter','justifyright','justifyjustify','|',
			'touppercase','tolowercase','|',
            'link','unlink','anchor','|',
			'imagenone','imageleft','imageright','imagecenter','|',
            'insertimage','emotion','scrawl','insertvideo','music','attachment','map','gmap','insertframe','insertcode','pagebreak','template','|',
			'horizontal','date','time','spechars','snapscreen','wordimage','|',
			'inserttable','deletetable','insertparagraphbeforetable','insertrow','deleterow','insertcol','deletecol','mergecells','mergeright','mergedown','splittocells','splittorows','splittocols','|',
			'print','preview','searchreplace','source','help'
		];
		$str='<script>';
		switch($type){
			case 'common':
				$conf=[
					'fullscreen',
					'bold','italic','underline','strikethrough','|','fontfamily', 'fontsize',
					'forecolor','backcolor','insertorderedlist','insertunorderedlist',
					'justifyleft','justifycenter','justifyright','justifyjustify','indent','|',					
					'inserttable','insertimage','emotion','insertvideo','map','link','|',
					'preview','source',
				];
			case 'rich':								//普通编辑
				//unset($conf[array_search('source',$conf)]);
				unset($conf[array_search('insertframe',$conf)]);
				unset($conf[array_search('insertcode',$conf)]);
				unset($conf[array_search('scrawl',$conf)]);
				unset($conf[array_search('attachment',$conf)]);
				unset($conf[array_search('snapscreen',$conf)]);
				break;
			case 'easy':								//简单
				$conf=[
					'bold','italic','underline','fontborder','strikethrough','superscript','subscript','removeformat','formatmatch','autotypeset','blockquote','pasteplain','|','customstyle', 'paragraph', 'fontfamily', 'fontsize',
				];
				break;
			case 'table':								//适合制作表编辑器
				$conf=[
					'fullscreen','bold','italic','underline','forecolor','backcolor','insertorderedlist','insertunorderedlist','|',
					'inserttable','deletetable','insertparagraphbeforetable','insertrow','deleterow','insertcol','deletecol','mergecells','mergeright','mergedown','splittocells','splittorows','splittocols',
				];
			case 'all':									//全部编辑
				unset($conf[array_search('scrawl',$conf)]);
				unset($conf[array_search('attachment',$conf)]);
				unset($conf[array_search('snapscreen',$conf)]);
				break;
		}
		$str.="var ".$name."_ueditor =new UE.ui.Editor({initialFrameWidth:'".$width."',initialFrameHeight:'".$height."',autoHeightEnabled:".($autoHeight==1?'true':'false').",";
		$conf=implode("','",$conf);
		$conf="'".$conf."'";
		$str.='toolbars:[['.$conf.']]});';
		$str.=$name."_ueditor.render('".$name."');</script>";
		echo $str;
	}
	
	//图库选择
	function opt_photo($val)
	{
	   return '<button class="pear-btn pear-btn-primary pear-btn-sm" style="vertical-align:top;" id="'.$val.'" type="button"><i class="icon pear-icon pear-icon-picture"></i> 图库选择</button>
	   <script>
	   layui.use(["jquery"],function() {
	    let $ = layui.jquery;
	    //弹出窗设置 自己设置弹出百分比
	    function screen() {
	        if (typeof width !== "number" || width === 0) {
	        width = $(window).width() * 0.8;
	        }
	        if (typeof height !== "number" || height === 0) {
	        height = $(window).height() - 20;
	        }
	        return [width + "px", height + "px"];
	    }
	    $("#'.$val.'").on("click", function () {
	        layer.open({
	            type: 2,
	            maxmin: true,
	            title: "图库选择",
	            shade: 0.1,
	            area: screen(),
	            content:"'.U('index/optPhoto').'",
	            success:function (layero,index) {
	                var iframe = window["layui-layer-iframe" + index];
	                iframe.child("'.$val.'")
	            }
	        });
	    });
	    })
	    </script>';
	}
	
	//返回通用的模板页面路径  该模板文件存放在前端的TPL文件夹下
	function public_tpl_path($name){
		$path=TMPL_PATH.$name;
		if(strpos($name,'.')==false){
			$path.=C('TMPL_TEMPLATE_SUFFIX');
		}
		return $path;
	}
	
	//容量单位转换
	function format_size($val,$k='kb',$len=1){
		switch($k){
			case 'kb':
				$val*=0.001;
				break;
			case 'mb':
				$val*=0.000001;
				break;
			case 'gb':
				$val*=0.000000001;
			default:
				break;
		}
		$val=format_number($val,'float',$len);
		return $val;
	}
	
	//长度截取
	function last_star($str,$num=3,$mark='*'){
		$len=strlen($str);
		$str=substr($str,0,-$num);
		$str=str_pad($str,$len,$mark);
		return $str;
	}
	
	//秒数格式化
	function secs_format($secs){
		if($secs<60){
			$str=$secs.'秒';
		}else if($secs>60 && $secs<3600){
			$str=floor($secs/60)."分";
			$s=intval($secs%60);
			if($s>0) $str.=$s.'秒';
		}else{
			$str=floor($secs/3600).'小时多';
		}
		return $str;
	}
	
	//客服代码
	function server_code($mark,$conf){
		switch($mark){
			case 'qq':
				return '<a title="点击这里给我发消息" href="http://wpa.qq.com/msgrd?v=3&amp;uin='.$conf.'&amp;site=QQ客服&amp;menu=yes" target="_blank"><img src="http://wpa.qq.com/pa?p=2:'.$conf.':41"></a>';
				break;
			case 'wang':
				return '<a target="_blank" href="http://amos.alicdn.com/getcid.aw?v=2&uid='.$conf.'&site=cntaobao&s=1&groupid=0&charset=utf-8"><img border="0" src="http://amos.alicdn.com/online.aw?v=2&uid='.$conf.'&site=cntaobao&s=1&charset=utf-8" alt="点击这里给我发消息" /></a>';
				break;
			default:
				return $conf;
				break;
		}
	}
	
	//显示单片段数据
	function onepart($part,$conf){
		$conf=explode('/',$conf);
		return @$part[$conf[0]][0][$conf[1]];
	}
	
	//把十六进制的颜色转化成RGB
	function hex2rgba($color, $raw = true , $opacity = false) {
	    $default = 'rgb(0,0,0)';
	    //Return default if no color provided
	    if(empty($color))
	          return $default; 
	    //Sanitize $color if "#" is provided 
	    if ($color[0] == '#' ) {
	        $color = substr( $color, 1 );
	    }
	    //Check if color has 6 or 3 characters and get values
	    if (strlen($color) == 6) {
	            $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
	    } elseif ( strlen( $color ) == 3 ) {
	            $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
	    } else {
	            $hex=[];
	    }
	 
	    //Convert hexadec to rgb
	    $rgb =  array_map('hexdec', $hex);
	    if($raw){
	        if($opacity){
	            if(abs($opacity) > 1) $opacity = 1.0;
	            array_push($rgb, $opacity);
	        }
	        $output = $rgb;
	    }else{
	        //Check if opacity is set(rgba or rgb)
	        if($opacity){
	            if(abs($opacity) > 1)
	                $opacity = 1.0;
	            $output = 'rgba('.implode(",",$rgb).','.$opacity.')';
	        } else {
	            $output = 'rgb('.implode(",",$rgb).')';
	        }
	    }
	 
	    //Return rgb(a) color string
	    return $output;
	}

	//***************************【面料模板调用函数】***********************************
	
	//面料颜色显示
	function markup($data){
		if($data!=''){
			$data=str_replace('#+','号色加',$data);
			$data=str_replace('/','元，',$data);
			$data.='元';
		}
		return $data;
	}

	//面料颜色转数组
	function markup_array($data){
		$data=explode('/',$data);
		$array=array();
		foreach ($data as $value) {
			$value=explode('#+',$value);
			$array[$value[0]]=$value[1];
		}
		return $array;
	}

	//毛重价转净布价
	function mtj_price($price,$tube,$emptykg){
		$ek=$tube+$emptykg;
		$mkg=28;
		$res=round($price*$mkg/($mkg-$ek),1);		//净布价格
		return price_one($res);
	}

	//净布价转毛重价
	function jtm_price($price,$tube,$emptykg){
		$ek=$tube+$emptykg;
		$mkg=28;
		$res=round($price*($mkg-$ek)/$mkg,1);
		return price_one($res);
	}
	
	//无空差转净布价
	function ktj_price($price,$tube,$emptykg){
		$ek=$tube;
		$mkg=28;
		$res=round($price*($mkg-$ek)/$mkg,1);		//净布价格
		return price_one($res);
	}
	
	//无空差转毛重价
	function ktm_price($price,$tube,$emptykg){
		$ek=$tube+$emptykg;
		$mkg=28;
		$res=round($price*($mkg-$ek)/($mkg-$tube),1);
		return price_one($res);
	}

	//利润
	function cloth_diff($v,$t=true){
		$ek=$v['emptykg']+$v['tube'];			//零售纸管空差
		$oek=$v['oemptykg']+$v['otube'];		//进货纸管空差
		$mkg=28;
		$diff = ($v['price1']*$mkg - $v['space1']*($mkg-$v['rebate_kg']))/$mkg;
		
		$diff=price_one($diff);

		if($t){
			if($diff<2){
				return '<label style="color:#CC0000">'.$diff.'</label>';
			}else if($diff>5){
				return '<label style="color:#269E26">'.$diff.'</label>';
			}else{
				return $diff;
			}	
		}else{
			return $diff;
		}
	}
	
	//二批价格与门市价的差价
	function cloth_diff2($v,$t=true){
		
		$diff = $v['ckprice1']-($v['price1']-cloth_diff($v,false));
		
		$diff=price_one($diff);
		
		if($t){
			if($diff>2){
				return '<label style="color:#269E26">'.$diff.'</label>';
			}else if($diff<=2 && $diff>0){
				return '<label style="color:#FF9800">'.$diff.'</label>';
			}else if($diff<=0){
				return '<label style="color:#CC0000">'.$diff.'</label>';
			}else{
				return $diff;
			}	
		}else{
			return $diff;
		}
	}
	
	// 虚假利润，把利润压缩成1元多，避免暴露
	function false_diff($v,$n=1,$t=true){
		if($n==1){
			$price=cloth_diff($v,$t);
		}else{
			$price=cloth_diff2($v,$t);
		}
		return round(cloth_diff($v,false)/10+1,2);
	}
	
	//折扣前价格取整
	function lvip_price($val,$zhe){
		$val=sprintf("%.1f", $val/$zhe);
		$min_int=explode('.',$val);
		if($min_int[1]<5){
			$val=$min_int[0];
		}else{
			$val=$min_int[0]+0.5;
		}
		return price_one($val);
	}
     /*
      *
      * @param timestamp $time 输入时间
      * @return str $str 输入时间与现在时间差的中文
      */
     function wordTime($time) {
         //dump($time);die;
		if($time=='' || $time==0){
			return '';
		}else{
			$time = (int) substr($time, 0, 10);
			$int = time() - $time;
			$str = '';
			if ($int <= 2) {
				$str = sprintf('刚刚', $int);
			} elseif ($int < 60) {
				$str = sprintf('%d秒前', $int);
			} elseif ($int < (60*60)) {
				$str = sprintf('%d分钟前', floor($int / 60));
			} elseif ($int < (24*60*60)) {
				$str = sprintf('%d小时前', floor($int / 3600));
			} elseif ($int < (30*24*60*60)) {
				$str = sprintf('%d天前', floor($int / 86400));
			} elseif ($int < (365*24*60*60)) {
				$str = sprintf('%d月前', floor($int / (30*24*60*60)));
			} elseif ($int < (3*365*24*60*60)) {
				$str = sprintf('%d年前', floor($int / (365*24*60*60)));
			} else {
				$str = date('Y-m-d H:i:s', $time);
			}
			return $str;
		}
     }
	 
	 //获取API接口的域名
	 function get_api_host($https=false){
		 $domains=env('route.domains',false);
		 $https=$https==true?'https://':'http://';
		 if($domains){
			 $host=$https.array_search('api',config('app.domain_bind'));
		 }else{
			 $host=$https.$_SERVER['HTTP_HOST'];
		 }
		 return $host;
	 }
?>